//
//  DDBossPublishJobViewController.m
//  DingDongZP
//
//  Created by Jyh on 16/4/21.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDBossPublishJobViewController.h"
#import "DDChooseJobCategoryViewController.h"
#import "DDTextFieldEditViewController.h"
#import "DDTextViewEditViewController.h"
#import "DDBossSkillRequirementTagViewController.h"

#import "DDCommonJobCell.h"
#import "DDPublishFooterView.h"
#import "DDBossInfoService.h"
#import "DDBossJobService.h"

#import "DDCommonDataModel.h"
#import "DDCityChooseView.h"


@interface DDBossPublishJobViewController () <UIActionSheetDelegate,UITextViewDelegate>

@property (strong, nonatomic) DDBossJobService *jobService;
@property (strong, nonatomic) DDBossInfoService *infoService;
@property (strong, nonatomic) DDPublishFooterView *footView;

@property (strong, nonatomic) NSMutableArray *eduArray;
@property (strong, nonatomic) NSMutableArray *experiencesArray;
@property (strong, nonatomic) NSMutableArray *provinceArray;
@property (strong, nonatomic) NSMutableArray *salaryArray;




@end

@implementation DDBossPublishJobViewController

- (instancetype)initWithType:(BossJobType)jobType
{
    self = [super init];
    if (self) {
        _jobType = jobType;
    }
    
    return self;
}

#pragma mark
#pragma mark - View LifeCycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.rdv_tabBarController setTabBarHidden:true animated:false];
    
    [self setupData];
    [self setupView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

#pragma mark
#pragma mark - Private Methods

- (void)setupData
{
    self.jobService = [[DDBossJobService alloc] init];
    self.infoService = [[DDBossInfoService alloc] init];
    if (!self.infoModel) {
        
        self.infoModel = [[DDPublishInfoModel alloc] init];
    }
    
    if (self.infoModel.skillrequirement_tagsNumber && [self.infoModel.jobskillrequirements count] > 0) {
        
        NSMutableDictionary *infos = [NSMutableDictionary new];
        infos[@"tagsNum"] = self.infoModel.skillrequirement_tagsNumber;
        
        NSMutableArray *tagIds = [NSMutableArray new];
        
        for (NSDictionary *dic in self.infoModel.jobskillrequirements) {
            [tagIds addObject:dic[@"tagid"]];
        }
        
        infos[@"tagsIDs"] = tagIds;
        
        self.infoModel.skillrequirement_tags = [infos jsonStringEncoded];
    }
    
    [self getCategoryIDFormNofi];
}

- (void)setupView
{
    self.title = @"发布职位";
//    self.tableView.rowHeight = 49;
    
    self.tableView.tableFooterView = self.footView;
    self.tableView.frame = self.view.frame;
    self.tableView.contentInset = UIEdgeInsetsMake(12, 0, 0, 0);
    if (self.jobType == BossJobTypeEdit) {
        // 编辑模式
        self.title = @"编辑职位";
        [self.footView.publishButton setTitle:@"保存" forState:UIControlStateNormal];
        self.footView.deleteButton.hidden = false;
        
        [self realoadTableView];
    } else {
        
        [self.footView.publishButton setTitle:@"发布" forState:UIControlStateNormal];
        self.footView.deleteButton.hidden = true;
    }
}

- (NSMutableArray *)getPublishJobTitleArray
{
    NSMutableArray *titles = [[NSMutableArray alloc] init];
    [titles addObject:@[@{@"title": @"职位类型"},
                        @{@"title": @"职位名称"},
                        @{@"title": @"技能要求"},
                        @{@"title": @"薪资范围"},
                        @{@"title": @"职位诱惑"}]];
    
    [titles addObject:@[@{@"title": @"经验要求"},
                        @{@"title": @"学历要求"}]];
    
    [titles addObject:@[@{@"title": @"工作城市"},
                        @{@"title": @"职位描述"}]];
    
    return titles;
}

#pragma mark
#pragma mark - Event Response

- (void)onPublishButtonClick:(UIButton *)button
{

    [self publishJobInfo];    
}

- (void)onDeleteButtonClick:(UIButton *)button
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要删除该职位?" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    WEAKSELF
    [alert bk_addButtonWithTitle:@"确定" handler:^{
        
        [weakSelf.jobService deleteJobInfoWithJobId:weakSelf.jobID SuccessBlock:^(id responseObject) {
            if ([weakSelf isValidateResponseData:responseObject]) {
                
                [weakSelf showToastOnCenter:@"删除成功"];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_BOSS_EDIT_JOBINFO object:nil];

                NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: weakSelf.navigationController.viewControllers];
                
                if ([navigationArray count] > 2) {
                    
                    [navigationArray removeObjectAtIndex:[navigationArray count] - 2];
                }
                
                weakSelf.navigationController.viewControllers = navigationArray;
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
            } else {
                [weakSelf responseUnValidate:responseObject];
            }
        } failBlock:^(id responseObject, NSError *error) {
            [weakSelf requestFaild];
        }];
    }];
    
    [alert show];
}

- (void)editJobInfoWithDic:(NSMutableDictionary *)dic
{
    WEAKSELF
    
    [self unEnableBtn];
    [[LDShowHUB shareInstance] showStaus:@"提交中..."];
    [self.jobService editJobInfoWithDictionary:dic SuccessBlock:^(id responseObject) {
        if ([weakSelf isValidateResponseData:responseObject]) {
//            NSLog(@"-修改职位返回数据---- %@",responseObject);
//            [weakSelf showText:@"修改成功"];
            [[LDShowHUB shareInstance] showSucc:@"提交成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_BOSS_EDIT_JOBINFO object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_BOSS_EDIT_PUBLISHINFO object:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        } else {
            
            [self enableBtn];
            [[LDShowHUB shareInstance] showSucc:@"提交失败"];
//            [weakSelf responseUnValidate:responseObject];
        }
    } failBlock:^(id responseObject, NSError *error) {
        
        [self enableBtn];
        [[LDShowHUB shareInstance] showErr:@"网络错误"];
//        [weakSelf requestFaild];
    }];
}

- (void) getCategoryIDFormNofi {
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:tapTagLabsViewNotiName object:nil] subscribeNext:^(NSNotification *noti) {
      
        [self.navigationController popViewControllerAnimated:false];
//        [self.navigationController popViewControllerAnimated:false];
        NSDictionary *dict = (NSDictionary *)noti.userInfo;
        
        self.infoModel.category_name = dict[@"tag"];
        self.infoModel.category_id = dict[@"index"];
        self.infoModel.job_title = dict[@"tag"];
        [self.tableView reloadData];
        
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:sendChose2TitleIDAndTitle object:nil] subscribeNext:^(NSNotification *noti) {
        
        NSDictionary *dict = (NSDictionary *)noti.userInfo;
        self.infoModel.lever2ID = dict[@"level2_id"];
        self.infoModel.lever2Name = dict[@"level2_name"];
        [self.tableView reloadData];
        
    }];
    
    
    
}

-(void)dealloc {
    
    [[LDShowHUB shareInstance] dissmiss];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)publishJobInfo
{
    NSMutableDictionary *jobDic = [@{} mutableCopy];
    
    
    
    if ([self.infoModel.category_id length] == 0) {
        [self showToastOnCenter:@"职位类型不能为空"];
        return;
    }
    if ([self.infoModel.job_title length] == 0) {
        [self showToastOnCenter:@"职位名称不能为空"];
        return;
    }
    if ([self.infoModel.jobskillrequirements count] == 0) {
        [self showToastOnCenter:@"技能要求不能为空"];
        return;
    }
    if ([self.infoModel.salary_id length] == 0) {
        [self showToastOnCenter:@"薪资范围不能为空"];
        return;
    }
    
    if ([self.infoModel.job_attraction length] == 0) {
        [self showToastOnCenter:@"职位诱惑不能为空"];
        return;
    }
    if ([self.infoModel.experience_id length] == 0) {
        [self showToastOnCenter:@"经验要求不能为空"];
        return;
    }
    if ([self.infoModel.edu_id length] == 0) {
        [self showToastOnCenter:@"学历要求不能为空"];
        return;
    }
    if ([self.infoModel.city_id length] == 0) {
        [self showToastOnCenter:@"工作城市不能为空"];
        return;
    }
    if ([self.infoModel.job_desc length] == 0) {
        [self showToastOnCenter:@"职位描述不能为空"];
        return;
    }
    
    
    jobDic[@"category_id"] = self.infoModel.category_id;
    jobDic[@"job_title"] = self.infoModel.job_title;
    jobDic[@"salary_id"] = self.infoModel.salary_id;
    jobDic[@"job_attraction"] = self.infoModel.job_attraction;
    jobDic[@"experience_id"] = self.infoModel.experience_id;
    jobDic[@"edu_id"] = self.infoModel.edu_id;
    jobDic[@"city_id"] = self.infoModel.city_id;
    jobDic[@"job_desc"] = self.infoModel.job_desc;
    jobDic[@"skillrequirement_tags"] = self.infoModel.skillrequirement_tags;
    
    if (self.jobType == BossJobTypeEdit) {
        
        jobDic[@"job_id"] = self.infoModel.jobId;
        [self editJobInfoWithDic:jobDic];
    } else {
        
        
         WEAKSELF
        [[LDShowHUB shareInstance] showStaus:@"提交中..."];
       
        self.footView.publishButton.enabled = false;
        [self.jobService creatJobInfoWithDictionary:jobDic SuccessBlock:^(id responseObject) {
            if ([weakSelf isValidateResponseData:responseObject]) {

                [[LDShowHUB shareInstance] showSucc:@"提交成功"];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_BOSS_EDIT_JOBINFO object:nil];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
            } else {
                
                [[LDShowHUB shareInstance] showSucc:@"提交失败"];
//                [weakSelf responseUnValidate:responseObject];
            }
        } failBlock:^(id responseObject, NSError *error) {
            
            self.footView.publishButton.enabled = true;
            [[LDShowHUB shareInstance] showErr:@"网络错误"];
//            [weakSelf requestFaild];
        }];
    }
}


- (void)showSalaryChoose
{
    
    WEAKSELF
    [[LDCheckPublicInfo shareInstance] checkoutAllSalary:^(NSArray<NSDictionary *> * _Nonnull data) {
        
        NSMutableArray *titleArr = [NSMutableArray array];
        NSMutableArray *titleIDArr = [NSMutableArray array];
        
        for (NSDictionary *experience in data) {
            
            DDCommonDataModel *model = [DDCommonDataModel yy_modelWithDictionary:experience];
            [titleArr addObject:model.salary_text];
            [titleIDArr addObject:model.salary_id];
        }
        
        [weakSelf showLDActionSheetView:@"设置薪资范围" labHeight:@35 labsTitleArr:titleArr selClosure:^(NSInteger index) {
            
            weakSelf.infoModel.salary_id = titleIDArr[index];
            weakSelf.infoModel.salary_name = titleArr[index];
            [weakSelf realoadTableView];
            
        }];
    
    }];
   
}

- (void)showExperienceChoose
{
    WEAKSELF
    [[LDCheckPublicInfo shareInstance] checkoutAllExperience:^(NSArray<NSDictionary *> * _Nonnull data) {
        
        NSMutableArray *titleArr = [NSMutableArray array];
        NSMutableArray *titleIDArr = [NSMutableArray array];
        
        for (NSDictionary *experience in data) {
            
            DDCommonDataModel *model = [DDCommonDataModel yy_modelWithDictionary:experience];
            [titleArr addObject:model.experience_text];
            [titleIDArr addObject:model.experience_id];
        }
        
        [weakSelf showLDActionSheetView:@"设置经验要求" labHeight:@35 labsTitleArr:titleArr selClosure:^(NSInteger index) {
            
            weakSelf.infoModel.experience_id = titleIDArr[index];
            weakSelf.infoModel.experience_name = titleArr[index];
            [weakSelf realoadTableView];
            
        }];
        
    }];
}

- (void)showEduChoose
{
    WEAKSELF
    [[LDCheckPublicInfo shareInstance] checkoutAllMainEduInfo:^(NSArray<NSDictionary *> * _Nonnull data) {
        
        NSMutableArray *titleArr = [NSMutableArray array];
        NSMutableArray *titleIDArr = [NSMutableArray array];
        
        for (NSDictionary *experience in data) {
            
            DDCommonDataModel *model = [DDCommonDataModel yy_modelWithDictionary:experience];
            [titleArr addObject:model.edu_text];
            [titleIDArr addObject:model.edu_id];
        }
        
        [weakSelf showLDActionSheetView:@"设置学历要求" labHeight:@35 labsTitleArr:titleArr selClosure:^(NSInteger index) {
            
            weakSelf.infoModel.edu_id = titleIDArr[index];
            weakSelf.infoModel.edu_name = titleArr[index];
            [weakSelf realoadTableView];
            
        }];
        
    }];
}

- (void)showCityChoose
{
    WEAKSELF
    DDCityChooseView *chooseCityView = [[DDCityChooseView alloc] initWithFrame:self.view.bounds];
    chooseCityView.selectedBlock = ^(NSString *cityName, NSString *cityId) {
        weakSelf.infoModel.city_name = cityName;
        weakSelf.infoModel.city_id   = cityId;
        
        [weakSelf realoadTableView];
    };
    [self.view addSubview:chooseCityView];
}

- (void)realoadTableView
{
    [self.tableView reloadData];
}

#pragma mark
#pragma mark - CustomDelegate

#pragma mark -
#pragma mark  UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self getPublishJobTitleArray][section] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self getPublishJobTitleArray].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CustomCellIdentifier = @"DDCommonJobCell";
    NSString *CustomCellJobID = @"DDCommonJobCellJobDetail";
    
    DDCommonJobCell *cell = (DDCommonJobCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"DDCommonJobCell" owner:self options:nil] lastObject];
    }
    
    DDBossPublishJobDetailDesc *detailJobCell = (DDBossPublishJobDetailDesc *)[tableView dequeueReusableCellWithIdentifier:CustomCellJobID];
    if (detailJobCell == nil) {
        
        detailJobCell = [[DDBossPublishJobDetailDesc alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CustomCellJobID];
        detailJobCell.descTextView.delegate = self;//.infoModel.job_
    }
    
    NSArray *array = [self getPublishJobTitleArray][indexPath.section];
    NSDictionary *dic = array[indexPath.row];
    cell.jobTitleLabel.text = dic[@"title"];
    
    switch (indexPath.section) {
        case 0:{
            switch (indexPath.row) {
                case 0:
                    // 职位类型
                    cell.subtextLabel.text = self.infoModel.category_name;
                    break;
                case 1:
                    // 职位名称
                    cell.subtextLabel.text = self.infoModel.job_title;
                    break;
                case 2:
                    // 技能要求
                    if (self.infoModel.skillrequirement_tagsNumber) {
                        cell.subtextLabel.text = [NSString stringWithFormat:@"%@个技能",self.infoModel.skillrequirement_tagsNumber];
                    }
                    break;
                case 3:
                    // 薪资范围
                    cell.subtextLabel.text = self.infoModel.salary_name;
                    break;
                case 4:
                    // 职位诱惑
                    cell.subtextLabel.text = self.infoModel.job_attraction;
                    break;
                    
                default:
                    break;
            }
        }
            break;
            
        case 1:{
            switch (indexPath.row) {
                case 0:
                    // 经验要求
                    cell.subtextLabel.text = self.infoModel.experience_name;
                    
                    break;
                case 1:
                    // 学历要求
                    cell.subtextLabel.text = self.infoModel.edu_name;
                    break;
                    
                default:
                    break;
            }
        }
            break;
            
        case 2:{
            switch (indexPath.row) {
                case 0:
                    // 工作城市
                    cell.subtextLabel.text = self.infoModel.city_name;
                    break;
                case 1:
                   // 职位描述
                    detailJobCell.title = @"职位描述";//getPublishJobTitleArray[2][1];
                    detailJobCell.desc = self.infoModel.job_desc;
                    return detailJobCell;
                    
                default:
                    break;
            }
        }
            break;
            
        default:
            break;
    }
    
    return cell;
}

#pragma mark -
#pragma mark  UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 2 && indexPath.row == 1) {
        
        return 220;
    }
    return 49;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIViewController *vc = nil;
    WEAKSELF
    switch (indexPath.section) {
        case 0:
        {
        
            switch (indexPath.row) {
                case 0:
                {
                    // 职位类别
                    LDBase2ChoseJobDetailsVC *job = [[LDBase2ChoseJobDetailsVC alloc] init];
                    job.title = @"选择职位";

                    vc = job;
                }
                    break;
                    
                case 1:
                {
                    // 职位名称
                    DDTextFieldEditViewController *textEdit = [[DDTextFieldEditViewController alloc] initWithMaxCharacterNumber:12];
                    textEdit.title = @"职位名称";
                    textEdit.value = self.infoModel.job_title;
                    textEdit.block = ^(NSString *text){
                        weakSelf.infoModel.job_title = text;
                        
                        [weakSelf realoadTableView];
//                        NSLog(@"----职位名称 text  %@",text);
                    };
                    vc = textEdit;
                }
                    break;
                case 2:
                {
                    // 技能要求
                
                    LDBossSkilTags *vc = [[LDBossSkilTags alloc] init];
                    vc.title = self.infoModel.lever2Name;
                    
                    
                    if (self.infoModel.category_id) {
                        
                        vc.leve2id = self.infoModel.lever2ID;
                    } else {
                        
                        [self showToastOnCenter:@"请先选择职位类型"];
                        return;
                    }
                    
                    WEAKSELF
                    [vc getParmasFromSelTags:^(NSDictionary<NSString *,id> * _Nonnull dict) {
                        
                        weakSelf.infoModel.skillrequirement_tags = [dict jsonStringEncoded];
                        weakSelf.infoModel.skillrequirement_tagsNumber = dict[@"tagsNum"];

                        NSString *jsonStr = [dict jsonStringEncoded];
                        
                        weakSelf.infoModel.skillrequirement_tags = jsonStr;
                        
                        NSMutableArray *tagsArr = [NSMutableArray array];
                        for (NSString *str in dict[@"tagsIDs"]) {
                            
                            NSDictionary *dict = @{@"tagid":str};
                            [tagsArr addObject:dict];
                        }
                        
                        weakSelf.infoModel.jobskillrequirements = tagsArr;
                        [weakSelf realoadTableView];
                        
                    }];
                    
                    NSMutableArray *mutarr = [NSMutableArray array];
                    for (NSDictionary *dict in self.infoModel.jobskillrequirements) {
                        
                    
                        if (dict[@"tagid"] != nil) {
                            
                            [mutarr addObject:dict[@"tagid"]];
                        }
                    }
                    vc.preSelHightIDParams = mutarr;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case 3:
                {
                    // 薪资范围
                    [self showSalaryChoose];
                }
                    break;
                    
                case 4:
                {
                    // 职位诱惑
                    DDTextFieldEditViewController *textEdit = [[DDTextFieldEditViewController alloc] initWithMaxCharacterNumber:25];
                    textEdit.title = @"职位诱惑";
                    textEdit.value = self.infoModel.job_attraction;
                    textEdit.block = ^(NSString *text){
                        if (text.length > 0) {
                            weakSelf.infoModel.job_attraction = text;
                            
                            [weakSelf realoadTableView];
                        }
                    };
                    vc = textEdit;
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
            
        case 1: {
            if (indexPath.row == 0) {
               // 经验要求
                [self showExperienceChoose];
            } else {
                //学历要求
                [self showEduChoose];
            }
        }
            break;
            
        case 2: {
            if (indexPath.row == 0) {
                // 工作城市
                [self showCityChoose];
                
            } else {
//                // 职位描述
//                DDTextViewEditViewController *textEdit = [[DDTextViewEditViewController alloc] initWithMaxCharacterNumber:500];
//                textEdit.title = @"职位描述";
//                textEdit.value = weakSelf.infoModel.job_desc;
//                textEdit.block = ^(NSString *text){
//                    if (text.length > 0) {
//                        weakSelf.infoModel.job_desc = text;
//                        
//                        [weakSelf realoadTableView];
//                    }
//                    
//                };
//                vc = textEdit;
            }
        }
            break;
        default:
            break;
    }
    
    if (vc) {
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

#pragma mark
#pragma mark - Getters and Setters

- (DDPublishFooterView *)footView
{
    if (!_footView) {
        _footView = (DDPublishFooterView *)[[NSBundle mainBundle] loadNibNamed:@"DDPublishFooterView" owner:self options:nil].firstObject;
        
        [_footView.publishButton addTarget:self action:@selector(onPublishButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [_footView.deleteButton addTarget:self action:@selector(onDeleteButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 235);
    }
    
    return _footView;
}

- (void)enableBtn {
    
    _footView.publishButton.enabled = true;
    _footView.deleteButton.enabled = true;
}

- (void)unEnableBtn {
    
    _footView.publishButton.enabled = false;
    _footView.deleteButton.enabled = false;
    
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [[[UIApplication sharedApplication] keyWindow] endEditing:true];
}

#pragma textDelegate

-(void)textViewDidEndEditing:(UITextView *)textView {
    
    self.infoModel.job_desc = textView.text;
}

@end
